package cn.myspringboot.config;

import cn.hutool.core.util.IdUtil;
import cn.myspringboot.constants.Constants;
import cn.myspringboot.constants.UserType;
import cn.myspringboot.mapper.LoginMapper;
import cn.myspringboot.pojo.domain.Login;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class BootstrapListener  implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private LoginMapper loginMapper;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Login login = loginMapper.selectOne(new LambdaQueryWrapper<Login>()
                .eq(Login::getUsername, Constants.System.ADMIN)
                .eq(Login::getName,Constants.System.ADMIN)
                .eq(Login::getType,UserType.admin));
        if(login == null) {
            Login login1 = new Login();
            login1.setUsername(Constants.System.ADMIN);
            login1.setName(Constants.System.ADMIN);
            login1.setType(UserType.admin);
            login1.setCreateTime(new Date());
            login1.setUpdateTime(new Date());
            long id = IdUtil.createSnowflake(0l, 0l).nextId();
            login1.setId(id);
            login1.setNickName(Constants.System.ADMIN);
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            String encode = bCryptPasswordEncoder.encode("123456");
            login1.setPassword(encode);
            login1.setAvatar("https://c-ssl.duitang.com/uploads/blog/202307/26/n6SDBG8Bs9AM3Xp.jpg");
            login1.setAdmin(true);
            login1.setEnabled(true);
            login1.setDeleted(false);
            loginMapper.insert(login1);
        }
    }
}